package com.mezizy.ifaner;


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;

import com.mezizy.ifaner.global.Global;
import com.mezizy.ifaner.global.com.mezizy.ifaner.web.data.Merchant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class StoreListTab extends Fragment {
    static ListView listStore;
    /*
    * test Adapter
    */
    static SimpleAdapter simpleAdapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.tab_store_list, container, false);
        listStore = (ListView) view.findViewById(R.id.listStore);
//        listStore.setAdapter(new ArrayAdapter<String>(MainActivity.getInstance(), android.support.v7.appcompat.R.layout.support_simple_spinner_dropdown_item, new String[]{"1", "2", "3"}));
//        dishAdapter = new zSimpleAdapter(MainActivity.getInstance(), getData(), R.layout.list_store, new String[]{"img", "storeName", "discount"}, new int[]{R.id.imgStore, R.id.txtStoreName, R.id.txtDiscount});
//
//        listStore.setAdapter(dishAdapter);

        new zAsync().execute();
        return view;
    }

    //TODO
    public static class zSimpleAdapter extends SimpleAdapter {
        int res;
        List<? extends Map<String, ?>> data;

        /**
         * Constructor
         *
         * @param context  The context where the View associated with this SimpleAdapter is running
         * @param data     A List of Maps. Each entry in the List corresponds to one row in the list. The
         *                 Maps contain the data for each row, and should include all the entries specified in
         *                 "from"
         * @param resource Resource identifier of a view layout that defines the views for this list
         *                 item. The layout file should include at least those named views defined in "to"
         * @param from     A list of column names that will be added to the Map associated with each
         *                 item.
         * @param to       The views that should display column in the "from" parameter. These should all be
         *                 TextViews. The first N views in this list are given the values of the first N columns
         */
        public zSimpleAdapter(Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to) {
            super(context, data, resource, from, to);
            if (this.res == 0) {
                this.res = resource;

            }
            if (this.data == null) {
                this.data = data;
            }


        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            View view = super.getView(position, convertView, parent);

            RatingBar rtbStoreRate = (RatingBar) view.findViewById(R.id.rtbStoreRate);
            rtbStoreRate.setRating(Integer.parseInt(data.get(position).get("rate").toString()));
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Global.showToast("!!");
                    Intent intent = new Intent(MainActivity.getInstance(), StoreActivity.class);
                    intent.putExtra("merchantId", String.valueOf(data.get(position).get("merchantId")));
                    intent.putExtra("storeName", (String) data.get(position).get("storeName"));


                    MainActivity.getInstance().startActivity(intent);
                }
            });


            view.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    switch (event.getAction()) {
                        case MotionEvent.ACTION_DOWN:
                             v.findViewById(R.id.linearStore).setBackgroundColor(MainActivity.getInstance().getResources().getColor(R.color.list_view_pressed_color));
                            break;

                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            v.findViewById(R.id.linearStore).setBackgroundColor(MainActivity.getInstance().getResources().getColor(android.R.color.white));


                            break;
                    }

                    return false;
                }
            });


            return view;

        }
    }

    private static List<Map<String, Object>> getData() {
        List<Map<String, Object>> list = new ArrayList<>();

//        for (int i = 0; i < 5; i++) {
//
//            Map<String, Object> map = new HashMap<>();
//            map.put("merchantId", "m001");
//            map.put("img", R.drawable.store_test_icon);
//            map.put("storeName", "大台北");
//            map.put("rate", 3);
//            map.put("discount", "本店满10减4;满17减7;满30减15，首单立减2元…");
//            list.add(map);
//        }


        return list;
    }
public static void startAsync() {
    new zAsync().execute();
}
    private static class zAsync extends AsyncTask<List<Merchant>, List<Merchant>, List<Merchant>> {


        @Override
        protected List<Merchant> doInBackground(List<Merchant>... params) {
            Global.showProgress(MainActivity.getInstance(), "正在加载");
            List<Merchant> merchants = null;
            try {
                merchants = Global.getMerchantList();
            } catch (Exception e) {
                e.printStackTrace();
            }


            return merchants;
        }


        @Override
        protected void onPostExecute(List<Merchant> merchants) {
            super.onPostExecute(merchants);
            List list = getData();
            if(merchants==null ||merchants.size()==0){
                return;
            }

            for (Iterator iterator = merchants.iterator(); iterator.hasNext(); ) {
                Merchant merchant = (Merchant) iterator.next();

                Map map = new HashMap<>();
                map.put("merchantId", merchant.getId());

                map.put("img", R.drawable.store_test_icon2);
                map.put("storeName", merchant.getName());
                map.put("rate", merchant.getStars());
                map.put("discount", merchant.getDiscountInf());
                list.add(map);
            }
            simpleAdapter = new zSimpleAdapter(MainActivity.getInstance(), list, R.layout.list_store, new String[]{"img", "storeName", "discount"}, new int[]{R.id.imgStore, R.id.txtStoreName, R.id.txtDiscount});
            listStore.setAdapter(simpleAdapter);
            Global.dismissProgress(MainActivity.getInstance());
        }
    }
}
